const WebSocket = require('ws');
const { generateMid, generateUuid } = require('../utils/xianyuUtils');

class XianyuWebSocket {
    constructor(cookiesStr, xianyuApis) {
        this.xianyuApis = xianyuApis;
        this.baseUrl = 'wss://wss-goofish.dingtalk.com/';
        this.cookiesStr = cookiesStr;
        this.cookies = this.transCookies(cookiesStr);
        this.myId = this.cookies['unb'];
        this.deviceId = this.generateDeviceId(this.myId);
        this.ws = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
    }

    /**
     * 转换Cookie字符串为对象
     */
    transCookies(cookiesStr) {
        const cookies = {};
        const cookiePairs = cookiesStr.split("; ");
        
        for (const pair of cookiePairs) {
            try {
                const [key, ...valueParts] = pair.split('=');
                cookies[key] = valueParts.join('=');
            } catch (error) {
                continue;
            }
        }
        
        return cookies;
    }

    /**
     * 生成设备ID
     */
    generateDeviceId(userId) {
        const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
        const uuid = [];
        
        for (let i = 0; i < 36; i++) {
            if (i === 8 || i === 13 || i === 18 || i === 23) {
                uuid[i] = "-";
            } else if (i === 14) {
                uuid[i] = "4";
            } else {
                const random = Math.floor(16 * Math.random());
                uuid[i] = chars[i === 19 ? (3 & random) | 8 : random];
            }
        }
        
        return uuid.join("") + "-" + userId;
    }

    /**
     * 连接到WebSocket服务器
     */
    async connect() {
        try {
            console.log('正在连接到闲鱼WebSocket服务器...');
            
            // 获取访问令牌
            const tokenResponse = await this.xianyuApis.getToken(this.cookies, this.deviceId);
            const accessToken = tokenResponse.data.accessToken;
            
            // 创建WebSocket连接
            this.ws = new WebSocket(this.baseUrl);
            
            this.ws.on('open', () => {
                console.log('WebSocket连接已建立');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                this.init();
            });
            
            this.ws.on('message', (data) => {
                this.handleMessage(data);
            });
            
            this.ws.on('close', () => {
                console.log('WebSocket连接已关闭');
                this.isConnected = false;
                this.handleReconnect();
            });
            
            this.ws.on('error', (error) => {
                console.error('WebSocket错误:', error);
                this.isConnected = false;
            });
            
        } catch (error) {
            console.error('连接失败:', error.message);
            throw error;
        }
    }

    /**
     * 初始化WebSocket连接
     */
    async init() {
        try {
            const tokenResponse = await this.xianyuApis.getToken(this.cookies, this.deviceId);
            const accessToken = tokenResponse.data.accessToken;
            
            const msg = {
                lwp: "/reg",
                headers: {
                    "cache-header": "app-key token ua wv",
                    "app-key": "34839810",
                    "token": accessToken,
                    "ua": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
                    "wv": "1.0"
                },
                body: []
            };
            
            await this.sendMessage(msg);
            console.log('WebSocket初始化完成');
            
        } catch (error) {
            console.error('初始化失败:', error.message);
        }
    }

    /**
     * 创建聊天会话
     */
    async createChat(toId, itemId = '891198795482') {
        const msg = {
            lwp: "/r/SingleChatConversation/create",
            headers: {
                mid: generateMid()
            },
            body: [
                {
                    pairFirst: `${toId}@goofish`,
                    pairSecond: `${this.myId}@goofish`,
                    bizType: "1",
                    extension: {
                        itemId: itemId
                    },
                    ctx: {
                        appVersion: "1.0",
                        platform: "web"
                    }
                }
            ]
        };
        
        await this.sendMessage(msg);
    }

    /**
     * 发送消息
     */
    async sendMsg(cid, toId, text) {
        const textContent = {
            contentType: 1,
            text: {
                text: text
            }
        };
        
        const textBase64 = Buffer.from(JSON.stringify(textContent)).toString('base64');
        
        const msg = {
            lwp: "/r/MessageSend/sendByReceiverScope",
            headers: {
                mid: generateMid()
            },
            body: [
                {
                    uuid: generateUuid(),
                    cid: `${cid}@goofish`,
                    conversationType: 1,
                    content: {
                        contentType: 101,
                        custom: {
                            type: 1,
                            data: textBase64
                        }
                    },
                    redPointPolicy: 0,
                    extension: {
                        extJson: "{}"
                    },
                    ctx: {
                        appVersion: "1.0",
                        platform: "web"
                    },
                    mtags: {},
                    msgReadStatusSetting: 1
                },
                {
                    actualReceivers: [
                        `${toId}@goofish`,
                        `${this.myId}@goofish`
                    ]
                }
            ]
        };
        
        await this.sendMessage(msg);
    }

    /**
     * 发送消息到WebSocket
     */
    async sendMessage(message) {
        if (this.ws && this.isConnected) {
            this.ws.send(JSON.stringify(message));
        } else {
            throw new Error('WebSocket未连接');
        }
    }

    /**
     * 处理接收到的消息
     */
    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log('收到消息:', message);
            
            // 这里可以添加具体的消息处理逻辑
            // 比如自动回复、消息过滤等
            
        } catch (error) {
            console.error('消息解析失败:', error.message);
        }
    }

    /**
     * 处理重连
     */
    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
            
            console.log(`${delay}ms后尝试重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connect();
            }, delay);
        } else {
            console.error('重连次数已达上限，停止重连');
        }
    }

    /**
     * 关闭连接
     */
    close() {
        if (this.ws) {
            this.ws.close();
        }
    }
}

module.exports = XianyuWebSocket;
